////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "BaseEntityChooserDialog.h"

#include "../ObjectHandler/Entity/BaseEntityHandler.hpp"
#include "SmegEditorFrame.h"

////////////////////////////////////////////////////////////
/// Construct the SmegEditorFrame
////////////////////////////////////////////////////////////
BaseEntityChooserDialog::BaseEntityChooserDialog( wxWindow* _pParent ) :
    BaseEntityChooserDialogGUI( _pParent ),
    m_pChosenEntityHandler( NULL )
{
    wxArrayString handlersToAvoid;
    Setup( handlersToAvoid );
}

////////////////////////////////////////////////////////////
/// Construct the SmegEditorFrame
////////////////////////////////////////////////////////////
BaseEntityChooserDialog::BaseEntityChooserDialog( wxWindow* _pParent, const wxArrayString& _HandlersToAvoid ) :
    BaseEntityChooserDialogGUI( _pParent ),
    m_pChosenEntityHandler( NULL )
{
    Setup( _HandlersToAvoid );
}

////////////////////////////////////////////////////////////
/// Setup the list
////////////////////////////////////////////////////////////
void BaseEntityChooserDialog::Setup( const wxArrayString& _HandlersToAvoid ) {
    SmegEditorFrame* pParent = dynamic_cast<SmegEditorFrame*>( GetParent() );

    if ( pParent ) {
        pParent->GetHandlers<BaseEntityHandler>( m_BaseEntityHandlersVec );

        for ( unsigned i = 0; i < m_BaseEntityHandlersVec.size(); ++i ) {
            if ( wxNOT_FOUND  == _HandlersToAvoid.Index( m_BaseEntityHandlersVec[i]->GetId() ) ) {
                m_BaseEntityList->Append( m_BaseEntityHandlersVec[i]->GetId() );
            }
        }
    }
    
    if ( 0 == m_BaseEntityHandlersVec.size() ) {
        Close(true);
    }
}

////////////////////////////////////////////////////////////
/// Event handlers
////////////////////////////////////////////////////////////
void BaseEntityChooserDialog::OnValidateBaseEntity( wxCommandEvent& event ) {
    if ( m_pChosenEntityHandler ) {
        Close(true);
    } else {
	    wxMessageBox(_T("You need to choose a Base Entity!\n"),
	                    _T("BaseEntity Chooser Error"),
	                    wxOK | wxICON_ERROR,
	                    this);
    }
}

void BaseEntityChooserDialog::OnCancelBaseEntity( wxCommandEvent& event ) {
    m_pChosenEntityHandler = NULL;
    Close(true);
}

void BaseEntityChooserDialog::OnChooseBaseEntity( wxCommandEvent& event ) {
    wxString chosenId( event.GetString() );

    for ( unsigned i = 0; i < m_BaseEntityHandlersVec.size(); ++i ) {
        if ( chosenId == m_BaseEntityHandlersVec[i]->GetId() ) {
             m_pChosenEntityHandler = m_BaseEntityHandlersVec[i];
        }
    }
}